package com.neusoft.bizcore.notice.notification.converter;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.notice.notification.dto.NoticeTemplateDTO;
import com.neusoft.bizcore.notice.notification.model.NoticeTemplate;
import com.neusoft.bizcore.notice.notification.model.NoticeTemplateAttachment;
import com.neusoft.bizcore.notice.notification.repository.NoticeTemplateRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.bizcore.web.utils.id.BaseIdGenerator;

@Component
public class NoticeTemplateConverter extends AbstractConverter<NoticeTemplate, NoticeTemplateDTO> {

    @Autowired
    private NoticeTemplateRepository noticeTemplateRepository;

    @Autowired
    private BaseIdGenerator noticeTemplateCodeGenerator;

    @Autowired
    private NoticeTemplateAttachmentConverter noticeTemplateAttachmentConverter;

    @Override
    public NoticeTemplate toModel(final NoticeTemplateDTO dto) {
        final NoticeTemplate model;
        if (dto.isNew()) {
            model = new NoticeTemplate();
            if (StringUtils.isNotBlank(dto.getCode())) {
                model.setCode(dto.getCode());
            } else {
                model.setCode(this.noticeTemplateCodeGenerator.generateCode());
            }
        } else {
            model = this.noticeTemplateRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());
        model.setType(dto.getType());
        if (dto.getTemplate() != null) {
            final NoticeTemplateAttachment attachment =
                    this.noticeTemplateAttachmentConverter.toModel(dto.getTemplate());
            attachment.setNoticeTemplate(model);
            model.setTemplate(attachment);
        }
        model.setUpdateTime(new Date());
        return model;
    }

    @Override
    public NoticeTemplateDTO toDTO(final NoticeTemplate model, final boolean forListView) {
        final NoticeTemplateDTO dto = new NoticeTemplateDTO();
        dto.setId(model.getId());
        dto.setCode(model.getCode());
        dto.setType(model.getType());
        dto.setName(model.getName());
        if (model.getTemplate() != null) {
            dto.setTemplate(this.noticeTemplateAttachmentConverter.toDTO(model.getTemplate()));
        }
        return dto;
    }

}
